package com.jinyi.wwdeng.ui.config.act

import android.content.Intent
import android.os.Environment
import android.view.Gravity
import android.view.View
import androidx.camera.core.AspectRatio
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import com.jinyi.base.base.BaseActivity
import com.jinyi.base.utils.BarUtils
import com.jinyi.base.utils.HHLog
import com.jinyi.base.utils.img.ImageUtil
import com.jinyi.wwdeng.R
import com.jinyi.wwdeng.databinding.ActFaceCameraBinding
import java.io.File
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

/**
 * JinYiTest
 * @Author wwdeng
 * @CreateTime: 2024/4/23 14:49
 * @Annotation：人脸拍照
 */
class FaceCameraAct: BaseActivity() {

    lateinit var binding: ActFaceCameraBinding

    private lateinit var cameraExecutor: ExecutorService
    private var imageCapture: ImageCapture? = null

    private var outputFile: File? = null
    override fun getRootView(): View {
        binding = ActFaceCameraBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initView() {
        setTitleBarVisibility(View.VISIBLE)
        setTitleBarColor(ContextCompat.getColor(this, R.color.color_353535))
        setBackBtnRes(R.mipmap.pic_back_white_icon)
        setRightBtnRes(R.mipmap.pic_kefu_white_icon)
        setTextTitle(getString(R.string.identity_authentication))
        setTextTitleColor(ContextCompat.getColor(this, com.jinyi.lib_base.R.color.color_ffffff))
        setTextTitleGravity(Gravity.CENTER)
        BarUtils.setStatusBarLightMode(this, false)

        initCamera()
        showTakeView()
    }

    override fun initListener() {
        //拍照
        binding.btnTakePhoto.setOnClickListener {
            takeFilePhoto()
        }
        //重拍
        binding.btnRemake.setOnClickListener {
            showToast("重拍")
        }
        //使用
        binding.btnUse.setOnClickListener {
            showToast("使用")
        }
    }

    override fun initData() {
        val filePath = Environment.getExternalStorageDirectory().toString() + File.separator + "DCIM/Camera/";
        outputFile = File(filePath,"${System.currentTimeMillis()}.jpg")
    }

    private fun initCamera(){
        binding.cameraView.maskView.setMaskColor(ContextCompat.getColor(this, R.color.color_353535))
        cameraExecutor = Executors.newSingleThreadExecutor()
        startCamera()
    }

    /**
     * 打开相机预览
     */
    private fun startCamera() {
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
        cameraProviderFuture.addListener(Runnable {
            val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
            val preview = Preview.Builder()
                .setTargetAspectRatio(AspectRatio.RATIO_16_9)
                .build()
                .also {
                    it.setSurfaceProvider(binding.cameraView.previewView.surfaceProvider)
                }
            imageCapture = ImageCapture.Builder().build()
            //打开前置摄像头
            val cameraSelector = CameraSelector.DEFAULT_FRONT_CAMERA
            try {
                cameraProvider.unbindAll()
                cameraProvider.bindToLifecycle(this, cameraSelector, preview,imageCapture)
            } catch(exc: Exception) {
            }
        }, ContextCompat.getMainExecutor(this))
    }

    /**
     * 拍照并保存到本地
     */
    private fun takeFilePhoto(){
        if (imageCapture != null){
            val fileDir = File(Environment.getExternalStorageDirectory().toString() + File.separator + "DCIM/Camera/");
            if (!fileDir.exists()){
                fileDir.mkdir()
            }
            //创建文件
            val imgFile = File(fileDir,System.currentTimeMillis().toString()+".jpg")
            if (imgFile.exists()){
                imgFile.delete()
            }
            //创建输出选项对象
            val metadata = ImageCapture.Metadata()
            metadata.isReversedHorizontal = true
            //创建文件
            val outputFileOptions = ImageCapture.OutputFileOptions.Builder(imgFile).setMetadata(metadata).build()
            //开始拍照
            imageCapture!!.takePicture(outputFileOptions,ContextCompat.getMainExecutor(this),object : ImageCapture.OnImageSavedCallback{
                override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
                    val imgUri = outputFileResults.savedUri
                    //刷新图库
                    sendBroadcast(Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE", imgUri))

//                    Thread{
//                        binding.cameraView.crop(outputFile,imgFile,0)
//                    }.start()

                    showToast("拍照成功")
                    HHLog.e("拍照成功>>>>>>>${imgUri!!.path}")

                    val imageView = binding.cameraView.preImageView
                    imageView.visibility = View.VISIBLE
                    ImageUtil.getInstance().loadImage(getContext(),imageView,imgUri!!.path)

                    showTakeCompleteView()
                }
                override fun onError(exception: ImageCaptureException) {
                    HHLog.e("拍照失败>>>>>>>${exception.message}")
                }
            })
        }
    }

    /**
     * 显示拍照View
     */
    private fun showTakeView(){
        binding.btnTakePhoto.visibility = View.VISIBLE
        binding.completeLayout.visibility = View.GONE
    }

    /**
     * 显示拍照完成View
     */
    private fun showTakeCompleteView(){
        binding.btnTakePhoto.visibility = View.GONE
        binding.completeLayout.visibility = View.VISIBLE
    }

    override fun onDestroy() {
        super.onDestroy()
        cameraExecutor.shutdown()
    }
}